package cn.edu.sdjzu.xg.bysj.service;


import cn.edu.sdjzu.xg.bysj.dao.SchoolDao;
import cn.edu.sdjzu.xg.bysj.domain.School;
import cn.edu.sdjzu.xg.bysj.exception.BysjException;
import util.JdbcHelper;
import util.Pagination;

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public final class
SchoolService {
	private static SchoolDao schoolDao= SchoolDao.getInstance();
	private static SchoolService schoolService=new SchoolService();


	public static SchoolService getInstance(){
		return schoolService;
	}

	public Collection<School> findAll(List conditionList,Pagination pagination) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		Collection<School> schools = schoolDao.findAll(conditionList,pagination,connection) ;
		JdbcHelper.close(connection);
		return schools;
	}

	public School find(Integer id) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		School school = schoolDao.find(id,connection);
		JdbcHelper.close(connection);
		return school;
	}

	public boolean update(School school) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		//将自动提交设为false,开始事务
		connection.setAutoCommit(false);
		Boolean updated =false;
		try {
			//增加用户
			updated = schoolDao.update(school,connection);
			//提交事务
			connection.commit();

		}catch (Exception e){
			//回滚
			connection.rollback();

		}finally {
			//将自动提交设为true，结束事务
			connection.setAutoCommit(true);
			JdbcHelper.close(connection);
		}
		return updated ;
	}

	public boolean add(School school) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		//将自动提交设为false,开始事务
		connection.setAutoCommit(false);
		Boolean added =false;
		try {
			//增加用户
			added = schoolDao.add(school,connection);
			//提交事务
			connection.commit();

		}catch (Exception e){
			//回滚
			connection.rollback();

		}finally {
			//将自动提交设为true，结束事务
			connection.setAutoCommit(true);
			JdbcHelper.close(connection);
		}
		return added ;
	}
	public boolean delete(Integer id) throws SQLException , BysjException {
		Connection connection = JdbcHelper.getConn();
		//将自动提交设为false,开始事务
		connection.setAutoCommit(false);
		Boolean deleted = false;
		if(DepartmentService.getInstance().
				countAll(SchoolDao.find(id,connection))!=0){
			throw new BysjException("存在下属院系，不能删除！");
		}
		try {
			//增加用户
			deleted = schoolDao.delete(id, connection);
			//提交事务
			connection.commit();

		} catch (Exception e) {
			//回滚
			connection.rollback();

		} finally {
			//将自动提交设为true，结束事务
			connection.setAutoCommit(true);
			JdbcHelper.close(connection);
		}
		return deleted;
	}
}